<template>
  <div class="login-container">
    <el-card class="login-box">
      <h2>管理员登录</h2>
      <el-form :model="form" label-width="80px">
        <el-form-item label="账号">
          <el-input v-model="form.username" placeholder="请输入管理员账号" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            v-model="form.password"
            :type="passwordVisible ? 'text' : 'password'"
            placeholder="请输入密码"
            :rules="[
              {
                required: true,
                pattern: /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_]).{8,18}$/,
                message: '密码必须为8-18位，包含数字、字母和特殊字符',
              },
            ]"
          >
            <template #suffix>
              <el-icon
                @click="passwordVisible = !passwordVisible"
                style="cursor: pointer"
              >
                <View v-if="passwordVisible" />
                <Hide v-else />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="验证码">
          <div style="display: flex; align-items: center">
            <el-input
              v-model="form.checkCode"
              placeholder="请输入验证码"
              style="width: 60%; margin-right: 10px"
            />
            <img
              :src="checkCodeImg"
              @click="refreshCheckCode"
              style="cursor: pointer; height: 32px"
            />
          </div>
        </el-form-item>
        <div class="button-group">
          <el-button type="primary" @click="handleLogin">登录</el-button>
          <el-button type="success" @click="showRegisterDialog = true">注册</el-button>
        </div>
      </el-form>

    <el-dialog v-model="showRegisterDialog" title="管理员注册" width="30%">
      <el-form :model="registerForm" label-width="80px">
        <el-form-item label="账号">
          <el-input v-model="registerForm.username" placeholder="请输入管理员账号" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="registerForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="registerForm.realname" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="验证码">
          <div style="display: flex; align-items: center">
            <el-input
              v-model="registerForm.checkCode"
              placeholder="请输入验证码(5分钟内)"
              style="width: 60%; margin-right: 10px"
            />
            <img
              :src="checkCodeImg"
              @click="refreshCheckCode"
              style="cursor: pointer; height: 32px"
            />
          </div>
        </el-form-item>
        <el-button type="primary" @click="handleRegister">注册</el-button>
      </el-form>
    </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { View, Hide } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import axios from "axios";
import querystring from 'querystring';

const form = ref({
  username: "",
  password: "",
  checkCode: "",
});

const checkCodeImg = ref("");
const checkCodeKey = ref("");
const passwordVisible = ref(false);
const showRegisterDialog = ref(false);
const registerForm = ref({
  username: "",
  password: "",
  phone: "",
  realname: "",
  checkCode: ""
});

const getCheckCode = async () => {
  try {
    const response = await fetch("api/admin/account/checkCode");
    const data = await response.json();
    checkCodeImg.value = data.data.checkCode;
    checkCodeKey.value = data.data.checkCodeKey;
  } catch (error) {
    console.error("获取验证码失败:", error);
  }
};

const refreshCheckCode = () => {
  getCheckCode();
};

getCheckCode();

const router = useRouter();


onMounted(() => {
  
});

const handleRegister = async () => {
  try {
    const response = await axios.post("api/admin/account/register",
      querystring.stringify({
        userName: registerForm.value.username,
        registerPassword: registerForm.value.password,
        phone: registerForm.value.phone,
        realName: registerForm.value.realname,
        checkCode: registerForm.value.checkCode,
        checkCodeKey: checkCodeKey.value
      })
    );
    const data = await response.data;
    if (data.code === 200) {
      ElMessage.success("申请注册成功");
      showRegisterDialog.value = false;
    } else {
      ElMessage.error(data.data.info);
    }
  } catch (error) {
    console.error("注册失败:", error);
    ElMessage.error("注册失败，请重试");
  }
};

const handleLogin = async () => {
  try {
    // const response = await fetch('api/admin/account/login',{
    //   method: 'POST',
    //   headers: {
    //     'Content-Type': 'application/json'
    //   },
    //   body: JSON.stringify({

    //     checkCode: form.value.checkCode,
    //     checkCodeKey: checkCodeKey.value,
    //     password: form.value.password,
    //     username: form.value.username,

    //   })
    // })

    const response = await axios.post("api/admin/account/login",
      querystring.stringify({ 
            checkCode: form.value.checkCode,
            checkCodeKey: checkCodeKey.value,
            password: form.value.password,
            username: form.value.username, 
      })
    );
    const data = await response.data;
    if (data.code === 200) {
      router.push("/admin-view");
    } else {
      ElMessage.error(data.data.info);
    }
  } catch (error) {
    console.error("登录失败:", error);
    ElMessage.error("登录失败，请重试");
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: #f0f2f5;
}

.login-box {
  width: 400px;
  padding: 2rem;
  border: 4px solid #409eff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(64, 158, 255, 0.2);
}

h2 {
  text-align: center;
  margin-bottom: 1.5rem;
  color: #2c3e50;
}

.button-group {
  display: flex;
  gap: 10px;
  margin-top: 1rem;
}

.button-group .el-button {
  flex: 1;
  margin-top: 0;
}
</style>